package com.music.muisc.controllers;

import com.music.muisc.dao.UnitRepository;
import com.music.muisc.entity.Unit;
import com.music.muisc.services.UnitService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.validation.Valid;
import java.util.List;

@Controller
@RequestMapping("units")
public class UnitController {

    @Autowired
    UnitService unitService;


    @GetMapping
    public String displayUnits(Model model){

        List<Unit> units = unitService.getAll();
        model.addAttribute("units",units);
        return "units/list-units";
    }


    @GetMapping("/new")
    public String displayUnitForm(Model model){
        Unit aUnit = new Unit();
        model.addAttribute("unit",aUnit);
        return "units/new-unit";
    }

    @PostMapping("/save")
    public String createUnit(Model model, @Valid Unit unit, Errors errors){
        if ( errors.hasErrors()) return "units/new-unit";
        //使用unit crudRepository保存到数据库
        unitService.save(unit);
        return "redirect:/units";
    }
}
